#!/usr/bin/env bash

set -e

# 判断系统是否有node命令
has_node() {
  # shellcheck disable=SC2046
  if [ -z $(command -v 'node') ]; then
    return 1
  else
    return 0
  fi
}

# 判断系统是否有nvm命令
has_nvm() {
  # shellcheck disable=SC2046
  if [ -z $(command -v 'nvm') ]; then
    return 1
  else
    return 0
  fi
}

print_env() {
  echo "内核信息"
  uname -a

  if has_node; then
    # shellcheck disable=SC2006
    echo "当前node版本是 `node -v`";
  fi
}

upgrade_node() {
  # 判断 node 是否存在
  local CURRENT_NODE_VERSION;
  echo 'test node'
  if has_node; then
    CURRENT_NODE_VERSION=$(node -v)
  fi

  # 先判断 nvm 是否存在，不存在，则安装之
  # 因镜像里nvm默认存在，该判断取消
  echo 'test nvm'
  if ! has_nvm; then
    echo 'start install  nvm...'
    curl -s -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
    . /opt/soft/nvm/nvm.sh
    # shellcheck disable=SC1090
    . ~/.bashrc
    export NVM_DIR="/opt/soft/nvm"
    [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
    # 重新刷新环境变量
    # shellcheck disable=SC1090
    source ~/.bashrc
    echo 'install nvm success'
  fi

  echo "CURRENT_NODE_VERSION=$CURRENT_NODE_VERSION"
  echo "NODE_VERSION=$NODE_VERSION"
  # lts版本
  # shellcheck disable=SC2053
  if [[ $CURRENT_NODE_VERSION == $NODE_VERSION || $CURRENT_NODE_VERSION == "v$NODE_VERSION" ]]; then
    echo 'node version identical'
  else
    echo 'start install node...'
    # export NVM_NODEJS_ORG_MIRROR=http://npm.taobao.org/mirrors/node
    nvm install "${NODE_VERSION}"
    nvm alias default "${NODE_VERSION}"
    nvm use "${NODE_VERSION}"
    echo 'install node success'
  fi
}

update_process() {
  # shellcheck disable=SC2002
  # shellcheck disable=SC2126
  # shellcheck disable=SC2155
  export CPU_NUM=$(cat /proc/cpuinfo | grep processor | wc -l)
  echo "Set process by cup number: $CPU_NUM"
  if [[ $CPU_NUM ]]; then
    sed -i'' "s/\"max\"/\"$CPU_NUM\"/g" ./deploy/process.json
    echo "Set process: $CPU_NUM success"
  else
    sed -i'' "s/\"max\"/\"4\"/g" ./deploy/process.json
    echo "Set process: 4 success"
  fi
}

execute() {
  # 加上--no-daemon前台启动，用于svc守护
    node ${DEPLOY_DIR}/deploy/deployer.js --source ${COS_SOURCE} --secretKey ${COS_SECRET_KEY} --uploadPath $TARGET_DIR --targetPath ${APPNAME}/ --env ${COS_ENV}
}

# shellcheck disable=SC1090
source ~/.bashrc
print_env
upgrade_node
execute